//
//  LXRHeadWindow.m
//  01- 百思不得姐
//
//  Created by mac on 16/6/29.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "LXRHeadWindow.h"

//全局Window
static UIWindow* window_;

@implementation LXRHeadWindow
/**接口*/
+(void)show{
    window_.hidden = NO;
}
+(void)hide{
    window_.hidden = YES;
}
/**初始化Window设置*/
+(void)initialize{
    window_ = [[UIWindow alloc]init];
    window_.frame = CGRectMake(0, 0, LXRScreenW, 20);
    window_.backgroundColor = [UIColor clearColor];
    //window级别设置为最高
    window_.windowLevel = UIWindowLevelAlert;
    //window创建手势
    [window_ addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(windowClick)]];
}
/**监听窗口的点击*/
+(void)windowClick{
    //取出系统Window
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    //递归从window找出ScrollView
    [self searchScrollViewInView:window];
    
}

/** 从父控件--->递归--->找出ScrollView */
+(void)searchScrollViewInView:(UIView*)superView{
    
    for (UIScrollView* subView in superView.subviews) {
        //转坐标系---->使convertRect:subView 按toView:keyWindow 转坐标系
        //得到subview在窗口中的frame
        CGRect newFrame = [subView.superview convertRect:subView.frame toView:nil];
        //得到window窗口bounds
        CGRect winBounds = [UIApplication sharedApplication].keyWindow.bounds;
        
        /**isShowingOnWindow判断值 (根据Hidden/透明度/坐标范围->判断一个空间是否真正显示在窗口范围内)*/
        BOOL isShowingOnWindow = !subView.isHidden&&subView.alpha>0.01&&CGRectIntersectsRect(newFrame, winBounds);
        
        //如果是ScrollView,滚动最顶部
        if ([subView isKindOfClass:[UIScrollView class]] && isShowingOnWindow) {
            
            [UIView animateWithDuration:0.25 animations:^{
                CGPoint offset = subView.contentOffset;
                offset.y = -subView.contentInset.top;
                [subView setContentOffset:offset];
            }];
        }
        // 继续查找子控件
        [self searchScrollViewInView:subView];
    }
}




@end
